﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using FA.FlightAttendant.Plugin;
using FA.FlightAttendant.Host;
using System.IO;
using FA.FlightAttendant.Properties;
using System.Windows;
using NLog;

namespace FA.FlightAttendant.View.Commands
{
	public class RemoveSimulatorCommand : ICommand
	{
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            Simulator sim = (Simulator)parameter;

            try
            {
                // Unregister from SimHost
                SimHost.Instance.UnregisterSimulator(sim, true);

                try
                {
                    // Remove from the XML file
                    string simulatorFile = Path.Combine(Environment.CurrentDirectory, Settings.Default.SimulatorsFile);
                    SimulatorFileWriter simFileWriter = new SimulatorFileWriter(simulatorFile);

                    simFileWriter.RemoveSimulator(sim.Name);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Unable to remove simulator from XML", ex);
                    MessageBox.Show(
                        "Unable to remove simulator from XML.\n\n" + ex.Message,
                        "Unable to unregister simulator",
                        MessageBoxButton.OK,
                        MessageBoxImage.Warning);
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Unable to unregister simulator.", ex);
                MessageBox.Show(
                    "Unable to unregister simulator.\n\n" + ex.Message,
                    "Unable to unregister simulator",
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning);
            }
        }

        public bool CanExecute(object parameter)
        {
            return (parameter != null) && (parameter is Simulator);
        }
	}
}
